<template>
	<div class="mainbody">
		<div class="location">
			<el-breadcrumb separator-class="el-icon-arrow-right">
				<el-breadcrumb-item>
					<i class="iconfont icon-home"></i>
					管理中心
				</el-breadcrumb-item>
				<el-breadcrumb-item>商城管理</el-breadcrumb-item>
				<el-breadcrumb-item>商品列表</el-breadcrumb-item>
			</el-breadcrumb>
		</div>

		<div class="toolbar-box" :style="heightToolsBar">
			<div class="list-box">
				<div class="l-list">
					<el-button-group>
						<el-button icon="el-icon-plus" @click="$common.linkUrl('/shop/goods/edit')">新增</el-button>
						<el-button icon="el-icon-s-check" @click="auditCheckAll">审核</el-button>
						<el-button icon="el-icon-circle-check" v-if="showImgList" @click="toggleCheckAll">
							<template v-if="!checkAll">
								全选
							</template>
							<template v-else>
								取消
							</template>
						</el-button>
						<el-button icon="el-icon-delete" @click="deleteCheckAll">删除</el-button>
					</el-button-group>
				</div>
				<div class="r-list">
					<div class="search-box">
						<el-input placeholder="输入关健字" v-model="keyword" @keyup.enter.native="initData" clearable>
							<el-button slot="append" icon="el-icon-search" @click="initData"></el-button>
						</el-input>
					</div>
					<div class="btn-box">
						<el-button-group>
							<el-button :icon="iconImgList" @click="toggleImgList"></el-button>
							<el-button :icon="iconToolsBar" @click="toggleToolsBar"></el-button>
						</el-button-group>
					</div>
				</div>
			</div>

			<div class="more-box">
				<dl>
					<dt>查找商户</dt>
					<dd>
						<el-select v-model="merchantId" filterable remote default-first-option 
							:remote-method="loadMerchant" @change="initData" placeholder="请选择...">
							<el-option v-for="item in merchantList"
									   :key="item.id"
									   :label="item.title"
									   :value="item.id">
							</el-option>
						</el-select>
					</dd>
				</dl>
				<dl>
					<dt>选择类别</dt>
					<dd>
						<el-select v-model="categoryId" @change="initData" placeholder="请选择...">
							<el-option :key="0" label="全部类别" :value="0"></el-option>
							<el-option v-for="item in categoryList"
								:key="item.id"
								:label="item.title"
								:value="item.id">
							</el-option>
						</el-select>
					</dd>
				</dl>
				<dl>
					<dt>选择品牌</dt>
					<dd>
						<el-select v-model="brandId" @change="initData" placeholder="请选择...">
							<el-option :key="0" label="全部品牌" :value="0"></el-option>
							<el-option v-for="item in brandList"
								:key="item.id"
								:label="item.title"
								:value="item.id">
							</el-option>
						</el-select>
					</dd>
				</dl>
				<dl>
					<dt>选择标签</dt>
					<dd>
						<el-select v-model="labelId" @change="initData" placeholder="请选择...">
							<el-option :key="0" label="全部标签" :value="0"></el-option>
							<el-option v-for="item in labelList"
								:key="item.id"
								:label="item.title"
								:value="item.id">
							</el-option>
						</el-select>
					</dd>
				</dl>
				<dl>
					<dt>审核状态</dt>
					<dd>
						<el-select v-model="isLock" @change="initData" placeholder="请选择">
							<el-option :key="-1" label="全部状态" :value="-1"></el-option>
							<el-option :key="0" label="正常" :value="0"></el-option>
							<el-option :key="1" label="未审核" :value="1"></el-option>
						</el-select>
					</dd>
				</dl>
				<dl>
					<dt>上架状态</dt>
					<dd>
						<el-select v-model="status" @change="initData" placeholder="请选择">
							<el-option :key="-1" label="全部状态" :value="-1"></el-option>
							<el-option :key="0" label="上架" :value="0"></el-option>
							<el-option :key="1" label="已下架" :value="1"></el-option>
						</el-select>
					</dd>
				</dl>
				<dl>
					<dt>发布日期</dt>
					<dd>
						<el-date-picker style="width:280px" v-model="dateRange"
							type="daterange"
							value-format="yyyy-MM-dd"
							start-placeholder="开始时间"
							end-placeholder="结束时间"
							@change="initData">
						</el-date-picker>
					</dd>
				</dl>
			</div>
		</div>

		<div class="content-box">
			<div class="img-list" v-loading="loading" v-if="showImgList">
				<el-card v-if="listData.length==0" class="nodata">暂无数据</el-card>
				<el-card v-for="(item,index) in listData" :key="index">
					<div class="lock" v-if="item.isLock==1">审核中</div>
					<div class="check">
						<el-checkbox v-model="item.checked"></el-checkbox>
					</div>
					<el-image class="pic" fit="contain" :src="$api.loadFile(item.imgUrl)" :preview-src-list="[$api.loadFile(item.imgUrl)]">
						<div slot="error" class="image-slot">
							<i class="el-icon-picture-outline"></i>
						</div>
					</el-image>
					<i class="absbg"></i>
					<h1>
						<span><a href="javascript:;" @click="$common.linkUrl('/shop/goods/edit/'+item.id)">{{item.title}}</a></span>
					</h1>
					<div class="price">
						<h3>售价<b>{{item.sellPrice}}</b>元</h3>
						<span>总库存 {{item.stockQuantity}}</span>
					</div>
					<div class="tools">
						<el-tag size="small" v-for="(citem,i) in item.categoryTitle.split(',')"
								:key="citem.index">
							{{ citem }}
						</el-tag>
					</div>
					<div class="foot">
						<p class="time">{{item.addTime}}</p>
						<span>
							<el-link :underline="false" title="编辑" icon="el-icon-edit-outline" @click="$common.linkUrl('/shop/goods/edit/'+item.id)"></el-link>
							<el-link :underline="false" title="删除" icon="el-icon-delete" @click="deleteItem(item.id)"></el-link>
						</span>
					</div>
				</el-card>
			</div>

			<el-card class="table-card" v-else>
				<el-table ref="multipleTable" v-loading="loading" :data="listData" stripe class="table-list" @selection-change="handleSelectionChange">
					<el-table-column type="selection" width="45"></el-table-column>
					<el-table-column label="商品名称" min-width="220">
						<template slot-scope="scope">
							<el-image class="pic" fit="contain" :src="$api.loadFile(scope.row.imgUrl)" :preview-src-list="[$api.loadFile(scope.row.imgUrl)]">
								<div slot="error" class="image-slot">
									<i class="el-icon-picture-outline"></i>
								</div>
							</el-image>
							<h4>{{scope.row.title}}</h4>
							<span class="date">
								<i class="el-icon-time"></i>
								{{scope.row.addTime}}
							</span>
						</template>
					</el-table-column>
					<el-table-column prop="categoryTitle" label="所属类别" min-width="160">
						<template slot-scope="scope">
							<div class="nowrap">
								<el-tag size="small" v-for="(item,index) in scope.row.categoryTitle.split(',')"
										:key="item.index">
									{{ item }}
								</el-tag>
							</div>
						</template>
					</el-table-column>
					<el-table-column prop="sellPrice" label="销售价" width="90"></el-table-column>
					<el-table-column prop="stockQuantity" label="库存" width="80"></el-table-column>
					<el-table-column label="排序" width="120" align="center">
						<template slot-scope="scope">
							<el-input-number size="mini" v-model="scope.row.sortId" @change="editSortId(scope.row.id, scope.row.sortId)" :min="-99999999" :max="99999999"></el-input-number>
						</template>
					</el-table-column>
					<el-table-column label="上架" width="80" align="center">
						<template slot-scope="scope">
							<el-switch :active-value="0" :inactive-value="1" v-model="scope.row.status" @change="editStatus(scope.row.id, scope.row.status)"></el-switch>
						</template>
					</el-table-column>
					<el-table-column label="状态" width="80">
						<template slot-scope="scope">
							<el-tag size="small" type="info" effect="dark" v-if="scope.row.isDelete==1">已删除</el-tag>
							<el-tag size="small" type="warning" effect="dark" v-else-if="scope.row.isLock==1">待审</el-tag>
							<el-tag size="small" type="success" effect="dark" v-else-if="scope.row.status==0">上架</el-tag>
							<el-tag size="small" type="warning" effect="dark" v-else-if="scope.row.status==1">下架</el-tag>
						</template>
					</el-table-column>
					<el-table-column fixed="right" label="操作" width="90">
						<template slot-scope="scope">
							<el-button size="mini" icon="el-icon-edit" @click="$common.linkUrl('/shop/goods/edit/'+scope.row.id)"></el-button>
							<el-button size="mini" type="danger" icon="el-icon-delete" @click="deleteItem(scope.row.id)"></el-button>
						</template>
					</el-table-column>
				</el-table>
			</el-card>

			<div class="pager-box">
				<el-pagination background
					:hide-on-single-page="false"
					@size-change="handleSizeChange"
					@current-change="handleCurrentChange"
					:current-page="pageIndex"
					:page-sizes="[10, 20, 50, 100]"
					:page-size="pageSize"
					layout="total, sizes, prev, pager, next, jumper"
					:total="totalCount">
				</el-pagination>
			</div>
		</div>
	</div>
</template>

<script>
	export default {
		data() {
			return {
				showToolsBar: false, //显示更多条件选项
				showImgList: true, //显示图片列表
				checkAll: false, //是否已全选
				heightToolsBar: 'height:60px', //工具栏高度
				iconToolsBar: 'iconfont icon-d-arrow-down', //更多按钮图标
				iconImgList: 'iconfont icon-list-txt',//切换按钮图标
				loading: false,
				merchantId: null,
				categoryId: 0,
				labelId: 0,
				brandId: 0,
				isLock: -1,
				status: -1,
				keyword: '',
				dateRange: [],
				totalCount: 0,
				pageSize: 10,
				pageIndex: 1,
				merchantList: [],
				categoryList: [],
				brandList: [],
				labelList: [],
				listData: [],
				
			}
		},
		methods: {
			//加载数据
			initData() {
				let _this = this;
				let sendUrl = "/admin/shop/goods";
				sendUrl += "?pageSize=" + _this.pageSize;
				sendUrl += "&pageIndex=" + _this.pageIndex;
				sendUrl += "&categoryId=" + _this.categoryId;
				sendUrl += "&brandId=" + _this.brandId;
				sendUrl += "&labelId=" + _this.labelId;
				sendUrl += "&isLock=" + _this.isLock;
				sendUrl += "&status=" + _this.status;
				if(_this.merchantId){
					sendUrl += "&merchantId=" + _this.merchantId;
				}
				if (_this.dateRange.length > 0) {
					sendUrl += "&startTime=" + _this.dateRange[0];
					sendUrl += "&endTime=" + _this.dateRange[1];
				}
				if (_this.keyword.length > 0) {
					sendUrl += "&keyword=" + encodeURI(_this.keyword);
				}
				_this.$api.request({
					url: sendUrl,
					beforeSend() {
						_this.loading = true
					},
					success(res) {
						_this.listData = res.data;
						let pageInfo = JSON.parse(res.headers["x-pagination"]);
						_this.totalCount = pageInfo.totalCount;
						_this.pageSize = pageInfo.pageSize;
						_this.pageIndex = pageInfo.pageIndex;
						_this.listData.forEach(row => {
							_this.$set(row, 'checked', false); //默认不选中
						});
					},
					error(err) {
						_this.listData = []
					},
					complete() {
						_this.loading = false
					}
				});
			},
			//初始化工具栏
			initLoad() {
				let _this = this;
				//加载分类列表
				_this.$api.request({
					url: '/admin/shop/category',
					success(res) {
						_this.categoryList = res.data
					}
				});
				//加载品牌列表
				_this.$api.request({
					url: '/admin/shop/brand/view/0',
					success(res) {
						_this.brandList = res.data;
					}
				});
				//加载标签列表
				_this.$api.request({
					url: '/admin/shop/label/view/0',
					success(res) {
						_this.labelList = res.data;
					}
				});
				//加载数据
				_this.initData();
			},
			//加载商家列表
			loadMerchant(query) {
				let _this = this;
				_this.$api.request({
					url: `/admin/merchant/view/5?keyword=${encodeURI(query)}`,
					success(res) {
						_this.merchantList = res.data;
						//console.log(res.data)
					}
				});
			},
			//切换更多查询条件
			toggleToolsBar() {
				this.showToolsBar = !this.showToolsBar
				if (this.showToolsBar) {
					this.heightToolsBar = "height:auto"
					this.iconToolsBar = 'iconfont icon-d-arrow-up'
				} else {
					this.heightToolsBar = "height:60px"
					this.iconToolsBar = 'iconfont icon-d-arrow-down'
				}
			},
			//切换图文列表方式
			toggleImgList() {
				this.showImgList = !this.showImgList
				if (this.showImgList) {
					this.iconImgList = 'iconfont icon-list-txt'
				} else {
					this.iconImgList = 'iconfont icon-list-img'
				}
			},
			//全选切换
			toggleCheckAll() {
				let _this = this; //当前页面
				if (_this.listData) {
					_this.listData.forEach(function (item, index) {
						if (!_this.checkAll) {
							item.checked = true
						} else {
							item.checked = false
						}

					});
				}
				_this.checkAll = !_this.checkAll
			},
			//单项删除
			deleteItem(val) {
				let _this = this; //当前页面
				//执行删除操作
				_this.$confirm('确认要删除该记录吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function () {
					_this.$api.request({
						method: 'delete',
						url: '/admin/shop/goods/' + val,
						loading: true,
						successMsg: '已删除成功',
						success(res) {
							_this.initData();//重新加载列表
						}
					});
			
				}).catch(function () { });
			},
			//多选删除
			deleteCheckAll() {
				let _this = this; //当前页面
				//获取选中值
				let delIds = [];//创建一个数组
				if (_this.listData) {
					_this.listData.forEach((item, index) => {
						if (item.checked) {
							delIds.push(item.id);
						}
					});
				}
				//检查是否有选中
				if (delIds.length == 0) {
					_this.$message({
						message: '请选择要删除的记录！',
						type: 'warning'
					});
					return false;
				}
				//执行删除操作
				_this.$confirm('确认要删除该记录吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function () {
					_this.$api.request({
						method: 'delete',
						url: '/admin/shop/goods?ids=' + delIds.toString(),
						loading: true,
						successMsg: '已删除成功',
						success(res) {
							_this.initData(); //重新加载列表
						}
					});
				}).catch(function () { });
			},
			//批量审核
			auditCheckAll() {
				let _this = this; //当前页面
				//获取选中值
				let checkIds = [];//创建一个数组
				if (_this.listData) {
					_this.listData.forEach((item, index) => {
						if (item.checked) {
							checkIds.push(item.id);
						}
					});
				}
				//检查是否有选中
				if (checkIds.length == 0) {
					_this.$message({
						message: '请选择要审核的记录！',
						type: 'warning'
					});
					return false;
				}
				//执行删除操作
				_this.$confirm('确认批量审核记录吗？', '提示', {
					confirmButtonText: '确定',
					cancelButtonText: '取消',
					type: 'warning'
				}).then(function () {
					_this.$api.request({
						method: 'put',
						url: '/admin/shop/goods?ids=' + checkIds.toString(),
						loading: true,
						successMsg: '批量审核完成',
						success(res) {
							_this.initData(); //重新加载列表
						}
					});
				}).catch(function () { });
			},
			//上下架操作
			editStatus(id, status) {
				this.$api.request({
					method: 'patch',
					url: '/admin/shop/goods/' + id,
					data: [{ "op": "replace", "path": "/status", "value": status }],
					success(res) { }
				});
			},
			//排序数字操作
			editSortId(id, sortId) {
				this.$api.request({
					method: 'patch',
					url: '/admin/shop/goods/' + id,
					data: [{ "op": "replace", "path": "/sortId", "value": sortId }],
					success(res) { }
				});
			},
			//选中第几行
			handleSelectionChange(val) {
				let _this = this; //当前页面
				_this.listData.forEach(function (item) {
					item.checked = false;
					val.forEach(function (x) {
						if (item.id == x.id) {
							item.checked = true;
						}
					});
				});
			},
			//每页显示数量
			handleSizeChange(val) {
				if (this.pageSize != val) {
					this.pageSize = val;
					this.initData();
				}
			},
			//跳转到第几页
			handleCurrentChange(val) {
				if (this.pageIndex != val) {
					this.pageIndex = val;
					this.initData();
				}
			},
		},
		created() {
			this.initLoad();
		},
		watch: {
			//监听页面切换初始化Table选中的复选框
			showImgList: {
				handler(val, oldVal) {
					let _this = this;
					if (!val && _this.listData) {
						_this.listData.forEach(function (row) {
							if (row.checked) {
								_this.$nextTick(function () {
									_this.$refs.multipleTable.toggleRowSelection(row);
								});
							}
						});
					}
				},
				immediate: false
			}
		},
	}
</script>